package demo.handler;

import demo.dto.ErrorInfo;
import demo.exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类
 * @author xiaoming
 * @version 1.0
 * @date 2019-04-20 17:05
 **/
@ControllerAdvice
// 通常和@ExceptionHandler 一起使用
public class GlobalExceptionHandler {
    private static final String DEFAULT_ERROR_VIEW = "error";

    /**
     * 统一异常处理
     */
    @ExceptionHandler(Exception.class)
    // 注解声明异常处理方法
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.setViewName(DEFAULT_ERROR_VIEW);
        return modelAndView;
    }
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> defaultJSONErrorHandler(HttpServletRequest request, MyException e) {
        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setMessage(e.getMessage());
        errorInfo.setData("NO DATA");
        errorInfo.setUrl(request.getRequestURL().toString());

        // test
//        if (ErrorInfo.ERROR != 0) {
//            throw new Exception("测试 throws Exception");
//        }
        return errorInfo;
    }

}
